//
//  STAvatarView.swift
//  Story
//
//  Created by 汤泽川 on 2019/4/9.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import SnapKit
import Kingfisher

class STAvatarView: UIView {
    let avatarImageView = UIImageView()
    let nameLabel = UILabel()
    let introduceLabel = UILabel()
    let alphaBtn = UIButton()
    private let avatarImageWidth = 50.0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        buildView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func buildView() {
        self.addSubview(avatarImageView)
        avatarImageView.layer.cornerRadius = CGFloat(avatarImageWidth / 2.0)
        avatarImageView.layer.masksToBounds = true
        
        self.addSubview(nameLabel)
        nameLabel.font = UIFont.boldSystemFont(ofSize: 17)
        nameLabel.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        
        self.addSubview(introduceLabel)
        introduceLabel.font = UIFont.systemFont(ofSize: 12)
        introduceLabel.textColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
        self.addSubview(alphaBtn)
    }
    
    public func update(user : STUserInfo?) {
        if let user = user {
            avatarImageView.kf.setImage(with: URL(string: user.avatarUrl ?? ""), placeholder: #imageLiteral(resourceName: "user_default"))
            nameLabel.text = user.username
            introduceLabel.text = user.introduce ?? "这家伙太懒了，没有填写自我介绍"
        } else {
            avatarImageView.image = #imageLiteral(resourceName: "user_default")
            nameLabel.text = "登陆/注册"
            introduceLabel.text = "登陆一下，内容更精彩"
        }
    }

    override func updateConstraints() {
        super.updateConstraints()
        
        avatarImageView.snp.updateConstraints { (make) in
            make.size.equalTo(CGSize(width: avatarImageWidth, height: avatarImageWidth))
            make.left.equalTo(self.snp_left)
            make.top.bottom.equalTo(self)
        }
        nameLabel.snp.updateConstraints { (make) in
            make.left.equalTo(avatarImageView.snp_right).offset(8)
            make.right.equalTo(self.snp_right)
            make.bottom.equalTo(avatarImageView.snp_centerY).offset(3)
            make.top.equalToSuperview()
        }
        introduceLabel.snp.updateConstraints { (make) in
            make.left.equalTo(avatarImageView.snp_right).offset(8)
            make.right.equalTo(self.snp_right)
            make.top.equalTo(avatarImageView.snp_centerY).offset(-3)
            make.bottom.equalToSuperview()
        }
        alphaBtn.snp.updateConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    public func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event) {
        alphaBtn.addTarget(target, action: action, for: controlEvents)
    }
}
